﻿using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SocketServer
{
    class Program
    {
        private static AutoResetEvent _flipFlop = new AutoResetEvent(false);
        static void Main(string[] args)
        {
            //创建socket，使用的是TCP协议，如果用UDP协议，则要用socketType.Dgram类型的Socket
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            //把ip和端口转化为IPEnding实例，端口号取8888
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 8096);

            Console.WriteLine("本地的ip地址端口是 : {0}", localEP);

            try
            {
                //绑定EndPoint对象（8888端口和ip地址）
                listener.Bind(localEP);
                //开始监听
                listener.Listen(10);
                //一直循环接受客户端的消息
                while (true)
                {
                    Console.WriteLine("等待Windows Phone客户端连接...");
                    //开始接受下一个连接
                    listener.BeginAccept(AcceptCallback, listener);
                    //开始等待线程
                    _flipFlop.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;
            Socket socket = listener.EndAccept(ar);

            Console.WriteLine("连接到Windows Phone客户端。");

            _flipFlop.Set();

            //开始接收，传递StateObject对象过去
            var state = new StateObject();
            state.Socket = socket;
            socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, state);

        }

        public static void ReceiveCallback(IAsyncResult ar) 
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket socket = state.Socket;

            //读取客户端Socket发送过来的数据
            int read = socket.EndReceive(ar);

            //如果成功读取了客户端Socket发送过来的数据
            if (read > 0)
            {
                //获取客户端的消息，转化为字符串格式
                string chunk = Encoding.UTF8.GetString(state.Buffer, 0, state.Buffer.Length);
                state.StringBuilder.Append(chunk);
                if (state.StringBuilder.Length > 0)
                {
                    string result = state.StringBuilder.ToString();
                    result = result.Substring(0, result.IndexOf(';'));
                    Console.WriteLine("收到客户端传过来的信息：{0}", result);
                    if (result == "Connected")
                    {
                        Send(socket, "Success");
                    }
                    else
                    {
                        Send(socket, result);
                    }
                }
            }
        }
        /// <summary>
        /// 返回客户端数据
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data"></param>
        private static void Send(Socket handler, String data)
        {
            //将消息内容转化为发送的byte[]格式
            byte[] byteData = Encoding.UTF8.GetBytes(data);

            //发送消息到Windows Phone客户端
            handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCellback), handler);
        }

        public static void SendCellback (IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket)ar.AsyncState;

                int bytesSent = handler.EndSend(ar);
                if (bytesSent > 0)
                {
                    Console.WriteLine("发送成功!");
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
